package com.cn.codebrush.字符串;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author Boolean
 * @Date 2022/5/21 14:24
 * @Version 1.0
 */
public class No3无重复字符的最长子串 {

    public static void main(String[] args) {
        String s = "abcababb";
        String s1 = "abba";
        System.out.println(lengthOfLongestSubstring3(s1));

    }






    /**
     * 解法三
     */
    public static int lengthOfLongestSubstring3(String s) {
        Map<Character,Integer> map = new HashMap<>();
        int start = 0;
        int res = 0;

        for(int i=0;i<s.length();i++){
            char ch = s.charAt(i);
            if(map.containsKey(ch)){
                start = Math.max(map.get(ch)+1,start);  //上一次已经比较过一次了，所以这次不比较了，比如，start=2，map.get(ch)+1 = 0；这个时候应该从2开始拼接
            }
            res = Math.max(res,i-start+1);
            map.put(ch,i);
        }

        return res;
    }

    /**
     * 解法二
     */
    public static int lengthOfLongestSubstring2(String s) {
        // 记录字符上一次出现的位置
        int[] last = new int[128];
        for(int i = 0; i < 128; i++) {
            last[i] = -1;
        }
        int n = s.length();

        int res = 0;
        int start = 0; // 窗口开始位置
        for(int i = 0; i < n; i++) {
            int index = s.charAt(i);
            start = Math.max(start, last[index] + 1);
            res   = Math.max(res, i - start + 1);
            last[index] = i;
        }

        return res;
    }

    /**
     * 解法一
     * @param s
     * @return
     */
    public int lengthOfLongestSubstring(String s) {
        String[] strings = s.split("");
        String str = strings[0];
        int res = str.length();

        for(int i=1;i<strings.length;i++){
            if(str.indexOf(strings[i]) == -1){
                str += strings[i];
                res = res>str.length()?res:str.length();
            }else {
                int cut = str.indexOf(strings[i]);
                str = str.length()>1?str.substring(cut+1)+strings[i]:str;
            }
        }

        return res;
    }

}
